const OSS = require('ali-oss');
const { v4: uuidv4 } = require('uuid');

const client = new OSS({
  region: process.env.ALIYUN_OSS_REGION,
  accessKeyId: process.env.ALIYUN_OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.ALIYUN_OSS_ACCESS_KEY_SECRET,
  bucket: process.env.ALIYUN_OSS_BUCKET
});

/**
 * 生成前端直传签名
 */
const MAX_SIZE = 10 * 1024 * 1024; // 10MB
const EXPIRE_TIME = 30 * 60 * 1000; // 30分钟有效期
const getUploadPolicy = async () => {
  const expireTime = Date.now() + EXPIRE_TIME; // 30分钟有效期
  const policy = {
    expiration: new Date(expireTime).toISOString(),
    conditions: [
      ['content-length-range', 0, MAX_SIZE], // 限制文件大小10MB
      ['starts-with', '$key', 'article-images/']
    ]
  };

  const formData = await client.calculatePostSignature(policy);

  return {
    OSSAccessKeyId: formData.OSSAccessKeyId,
    policy: formData.policy,
    signature: formData.Signature,
    prefix: 'article-images/',
    host: `https://${process.env.ALIYUN_OSS_BUCKET}.${process.env.ALIYUN_OSS_REGION}.aliyuncs.com`,
  };
};

module.exports = {
  getUploadPolicy
}